package cn.lin.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cn.Lin
 * @create 2024-12-03-10:44
 */
public class PdfUtil {

    /**
     * @param source      原文件
     */
    public static List<String> pdf2Png(String source) {
        OSS ossClient = null;
        PDDocument doc = null;
        List<String> urls = new ArrayList<>();
        try {

            ossClient = new OSSClientBuilder().build(OSSUtil.endpoint, OSSUtil.accessKeyId, OSSUtil.accessKeySecret);

            String fixedName = ".oss-cn-beijing.aliyuncs.com/";
            int bucketEndIndex = source.indexOf(fixedName);

            String bucketName = source.substring(8, bucketEndIndex);
            String imageName = source.substring(bucketEndIndex + fixedName.length());
            InputStream inputStream = ossClient.getObject(bucketName,imageName).getObjectContent();

            //加载PDF文件
            doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);

            //获取PDF文档的页数
            int pageCount = doc.getNumberOfPages();
            System.out.println("文档一共" + pageCount + "页");
            List<Object> fileList = new ArrayList<>();
            for (int i = 0; i < pageCount; i++) {
                //每一页通过分辨率和颜色值进行转化
                BufferedImage bufferedImage = renderer.renderImageWithDPI(i, 96 * 2, ImageType.RGB);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage,"png",baos);
                byte[] data = baos.toByteArray();

                // 准备文件名
                String fileName = (i + 1) + ".png";

                //将字节数组转换为输入流
                ByteArrayInputStream bais = new ByteArrayInputStream(data);

                //上传到服务器
                String url = OSSUtil.upload(fileName,bais);
                urls.add(url);

                baos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件处理异常");
            return null;
        } finally {
            try {
                if (doc != null) {
                    doc.close();
                }
            } catch (IOException e) {
                System.out.println("关闭文档失败");
                e.printStackTrace();
            }
        }
        return urls;
    }

}
